<template>
	<div>
		<el-form class="query-form" :model="query_params">
			<el-row>
		    <el-col class="query-item" :span="6">
					<el-form-item label="活动名称" prop="name">
						<el-input v-model="query_params.name"  autocomplete="off" />
					</el-form-item>
				</el-col>
				<el-col class="query-item" :span="6">
					<el-form-item >
						<el-button type="primary" @click="search">搜索</el-button>
					</el-form-item>
				</el-col>

		  </el-row>
		</el-form>
		<el-row class="add-box-css"><el-button type="primary" @click="activity_operation()">新增</el-button></el-row>
		<el-table :data="tableData" border style="width: 100%">
		    <el-table-column label="序号" width="180" >
				<template #default="scope">
		            {{scope.$index+1}}
		        </template>
		    </el-table-column>
		    <el-table-column prop="name" label="活动名称" />
		    <el-table-column prop="store_name" label="所属门店" />
		    <!-- <el-table-column prop="name" label="所属门店">
		    	<template #default="scope">
		    		{{getStore(scope.row)}}
		    	</template>
		    </el-table-column> -->
		    <el-table-column prop="eventsDesc" label="活动简介" />
		    <!-- <el-table-column prop="pricing" label="原价" /> -->
				<!-- <el-table-column prop="price" label="现价" /> -->
				<!-- <el-table-column prop="disable" label="状态" >
					<template #default="scope">
							{{getStatus(scope.row)}}
					</template>
				</el-table-column> -->
		    <el-table-column  label="状态" >
		      <template #default="scope">
		      	<div>{{!scope.row.disable?'正常':'禁用'}}</div>
		    		<!-- <el-switch  v-model="scope.row.disable" @click="confirm(scope.row)"/> -->
		      </template>
			</el-table-column>
			<el-table-column prop="end_time" label="截止日期" />
			<el-table-column  label="操作" >
		    	<template #default="scope">
		    		<el-button type="primary" size="small" @click="activity_operation(scope.row)">编辑</el-button>
		    		<el-button type="danger" size="small" @click="del_fun(scope.row)">删除</el-button>
		     	</template>
			</el-table-column>
		</el-table>
		<div class="pagination_box">
			<el-pagination background layout="prev, pager, next"  :total="total" @current-change="handleCurrentChange" />
		</div>
		<!-- 新增 & 编辑 -->
		<div>
			<el-drawer v-model="drawer"  size='60%' :with-header="false">
			    <template #default>
			      <div>
							<el-form
							    ref="ruleFormRef"
							    :model="ruleForm"
							    status-icon
							    :rules="rules"
							    label-width="120px"
							    class="demo-ruleForm"
							    :loading="loading"
							  >
							    <el-form-item label="活动名称" prop="name">
							      <el-input v-model="ruleForm.name"  autocomplete="off" />
							    </el-form-item>
							    <el-form-item label="活动简介" prop="eventsDesc">
							      <el-input v-model="ruleForm.eventsDesc"  autocomplete="off" />
							    </el-form-item>
							    <el-form-item label="截止日期" prop="end_time">
							      <el-date-picker
							        v-model="ruleForm.end_time"
							        type="date"
							        placeholder="选择截止日期"
							        size=""
							        value-format="YYYY-MM-DD"
							        format="YYYY-MM-DD"
							      />
							    </el-form-item>
							    <el-form-item label="所属门店" prop="storeId" :rules="[
						        { required: true, message: '请选择所属门店',trigger: 'blur' }
						      ]">
									<el-select v-model="ruleForm.storeId" class="m-2" placeholder="请选择所属门店">
								    <el-option
								      v-for="item in storeList"
								      :key="item.id"
								      :label="item.name"
								      :value="item.id"
								    />
								  </el-select>
								</el-form-item>
							    <!-- <el-form-item label="原价" prop="pricing">
							      <el-input v-model="ruleForm.pricing"  autocomplete="off" />
							    </el-form-item>
							    <el-form-item label="现价" prop="price">
							      <el-input v-model="ruleForm.price"  autocomplete="off" />
							    </el-form-item> -->
									<el-form-item label="活动头部图片" prop="headImg">
								     <el-upload
											    v-model:file-list="activity_headImg"
											    :action="action"
											    :auto-upload="true"
											    list-type="picture-card"
											    :on-preview="handlePictureCardPreview"
											    :on-remove="handleRemove"
											    :on-change="handleChange(0,'activity_headImg')"
											    :http-request="uploadAction"
											  >
										    <el-icon><Plus /></el-icon>
										 </el-upload>
									</el-form-item>
									<el-form-item label="活动主图" prop="masterImg">
								     <el-upload
											    v-model:file-list="activity_masterImg"
											    :action="action"
											    :auto-upload="true"
											    list-type="picture-card"
											    :on-preview="handlePictureCardPreview"
											    :on-remove="handleRemove"
											    :on-change="handleChange(0,'activity_masterImg')"
											    :http-request="uploadAction"
											  >
										    <el-icon><Plus /></el-icon>
										  </el-upload>
									</el-form-item>
									<el-form-item label="活动须知图片" prop="notice">
								     <el-upload
											    v-model:file-list="activity_notice"
											    :action="action"
											    :auto-upload="true"
											    list-type="picture-card"
											    :on-preview="handlePictureCardPreview"
											    :on-remove="handleRemove"
											    :on-change="handleChange(0,'activity_notice')"
											    :http-request="uploadAction"
											  >
										    <el-icon><Plus /></el-icon>
										  </el-upload>
							    </el-form-item>
									<el-form-item label="活动详情图" prop="descImg">
								     <el-upload
											    v-model:file-list="activity_descImg"
											    :action="action"
											    :auto-upload="true"
											    list-type="picture-card"
											    :on-preview="handlePictureCardPreview"
											    :on-remove="handleRemove"
											    :on-change="handleChange(0,'activity_descImg')"
											    :http-request="uploadAction"
											  >
										    <el-icon><Plus /></el-icon>
										  </el-upload>
							    </el-form-item>
									<el-form-item label="活动视频" prop="video" >
									     <el-progress
							                v-if="loading"
							                :text-inside="loading"
							                :stroke-width="15"
							                :percentage="percentage"
							                style="width: 40%"
							              />
									     <el-upload class="video_box"
										    v-model:file-list="activity_video"
										    :action="action"
										    :auto-upload="true"
										    list-type="picture-card"
										    :on-preview="handlePictureCardPreview"
										    :on-remove="handleRemove"
										    :on-change="handleChange(0,'activity_video')"
										    :http-request="uploadAction_video"
										  >
										    <el-icon><Plus /></el-icon>
										    <!-- 自定义缩略图 -->
										    <template #file="{ file }">
										      <div>
										        <span class="el-upload-list__item-actions">
										          <!-- 下载 -->
										          <span
										            class="el-upload-list__item-delete"
										            @click="handleDownload(file)"
										          >
										            <el-icon><zoom-in /></el-icon>
										          </span>
										          <!-- 移除 -->
										          <span
										            class="el-upload-list__item-delete"
										            @click="handleRemove_video(file)"
										          >
										            <el-icon><Delete /></el-icon>
										          </span>
										        </span>
										      </div>
										    </template>
										  </el-upload>
							    </el-form-item>
								<el-form-item label="是否禁用">
							      <el-switch v-model="ruleForm.disable" :active-value="1" :inactive-value="0" />
							    </el-form-item>
							    <el-form-item >
							      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
							    </el-form-item>
							</el-form>
			      </div>
			    </template>
			  </el-drawer>
		</div>
		<!-- 图片预览 -->
		<el-dialog v-model="dialogVisible">
	    <img w-full :src="dialogImageUrl" alt="Preview Image" />
	  </el-dialog>
	</div>
</template>
<script type="text/javascript">
	import {  ElMessageBox ,ElMessage} from 'element-plus'
	import { clients, getNowDate } from '@/utils/index'
	import api from "@/api/store/store"
	export default {
		data(){
			return {
				action:'',
				queryForm:{},
				query_params:{
					current:1,
					size:10
				},
				tableData:[],
				total:0,
				drawer:false,
				// 表单
				ruleFormRef:{},
				ruleForm :{
				},
				rules:{
				  name: [
				    { required: true, message: '请输入商户', trigger: 'blur' },
				  ],
				},
				activity_headImg:[],//活动头部图片
				activity_masterImg:[],//活动主图片
				activity_descImg:[],//活动详情图片
				activity_notice:[],//活动须知图片
				activity_video:[],//活动视频
				loading:false,
				//预览图片
				dialogVisible:false,
				dialogImageUrl:'',//预览地址,
				storeList:[],// 门店列表
			}
		},
		methods:{
			del_fun(row){ // 删除数据
				console.log(row)
				ElMessageBox.alert('确定要删除该数据吗？', '提示', {
				    confirmButtonText: '确定',
				    callback:async action => {
					  console.log(action)
					  if(action == "confirm"){
					  		const res = await api.delActivity(row);
					  		if(res?.code == 200) {
					  		  ElMessage({
						        type: 'success',
						        message: '删除成功',
						      })
						      this.getList();
					  		}
					  }
				      
				    },
				 })
			},
			async submitForm(val){//提交表单
				this.cardParams();//梳理参数
				// console.log(this.ruleForm);return
				const res = await api.addActivity(this.ruleForm)
				if(res.code == 200) {
					ElMessage({
				        type: 'success',
				        message: '操作成功',
				    })
				    this.drawer = false;
					this.getList();
				}
			},
			cardParams(){
				//文件相关
				const fields=['headImg','video','masterImg','descImg','notice'];//文件名
				var prefix="activity_";
				for(let val of fields){
					let name=prefix+val;
					if(this[name].length>0){
							let new_list = [];
							for(let item of this[name]){
								if(item.url){
									new_list.push(item.url)
								}
							}
							this.ruleForm[val] = new_list.join(",")
					}
					else{
						this.ruleForm[val] = ""
					}
				}
				console.log(this.ruleForm.video)
				//控制传参
				if(this.ruleForm.createdAt) delete this.ruleForm.createdAt
				if(this.ruleForm.updatedAt) delete this.ruleForm.updatedAt
				this.ruleForm.price = parseFloat(this.ruleForm.price)
				this.ruleForm.pricing = parseFloat(this.ruleForm.pricing)
			},
			search(){
				this.query_params.current=1;
				this.query_params.size=10;
				this.getList()
			},
			activity_operation(row){//编辑或新增活动
				this.drawer=true
				if(row){//编辑
					//填充数据
					this.ruleForm=row;
					//梳理文件数据
					this.cardDataEdit(row)
				}
				else{//新增
					this.ruleForm={}
					//清除所有文件数组
					this.clearFiles()
				}
			},
			clearFiles(){
				const fields=['headImg','masterImg','descImg','notice','video'];//文件字段名
				var prefix="activity_";//前缀
				for(let val of fields){
					let name=prefix+val
					this[name]=[];
				}
			},
			cardDataEdit(row){//梳理文件数据
				const fields=['headImg','masterImg','descImg','notice','video'];//文件名
				var prefix="activity_";
				for(let prop of fields){
					let name=prefix+prop;
					this[name]=[];
					if(row[prop]){
						var activity_obj = row[prop].split(",");
						var new_list=[];
						for (let val of activity_obj){
								let new_img = {
										content: val,
										url: val
								}
								new_list.push(new_img)
						}
						this[name] = new_list;
					}
				}
			},
			getStatus(row){//查询状态
				// console.log(row);
				var str="正常"
				if(!row.disable){
					str="已禁止"
				}
				return str
			},
			handleCurrentChange(val){
				console.log(val)
				this.query_params.current=val;
				this.getList();
			},
			async getList(){
				const res = await api.getActivityList(this.query_params)
				if(res.code == 200 ) {
					this.tableData=res.data.records;
					if(this.total<1){
						this.total=parseInt(res.data.total)
					}
					// 获取门店列表
					api.getStoreList({
						current:1,
						size:100
					}).then(res2=>{
						this.storeList = res2.data.records
					})
				}
			},
			async uploadAction(file){//文件上传
				// console.log(file);
				file.status = 'uploading';
        file.message = '上传中...';
        //开始上传
        const content = new FormData();
        //上传图片需要转换二进制这里要用到FormData
        content.append("file", file.file);
				const res=await this.$API.upload(content);
				if(res.code==200){
					file.status = 'done';
					file.message = '上传成功';
					file.url = res.data;
				}
				else{
					file.status = 'failed';
					file.message = '上传失败';
				}
				//重新赋值  img/视频
				for(let item of this[this.list_type]){
					if(item.uid==file.file.uid){
						item.url=file.url
					}
				}
				// console.log(this[this.list_type]);
			},
			handleChange(i,type){
				this.list_type=type
				if(type=='normsList'){
					this.current_norms=i
				}
			},
			handlePictureCardPreview(uploadFile){//预览文件
				this.dialogImageUrl=uploadFile.url
				this.dialogVisible=true
			},
			handleRemove(uploadFile, uploadFiles){

			},
			//移除视频
			handleRemove_video(file){
				for(let i=0;i<this.activity_video.length;i++){
					if(this.activity_video[i].uid==file.uid){
						this.activity_video.splice(i,1)
					}
				}
			},
			//视频上传
			handleDownload(file){//下载视频
				// console.log(file)
				// location.href=file.url
				window.open(file.url,'_blank');
			},
			//视频切片上传
			async uploadAction_video(file){
				// console.log(file)
				try {
			        // 判断扩展名
			        const tmpcnt = file.file.name.lastIndexOf('.')
			        const exname = file.file.name.substring(tmpcnt + 1)
			        const client = clients()
			        const names = ['wav', 'mp4']
			        if (names.indexOf(exname) < 0) {
			          this.$message.error('不支持的格式!')
			          return
			        }
			        this.loading = true
			        // const imgUrl = 'http://work.hezonglianmeng.com'
			        const imgUrl = 'https://workflow-zym.oss-cn-shanghai.aliyuncs.com'
			        const fileName = `static/uploadfile/${getNowDate()}/${
			          file.file.uid
			        }.${exname}`
			        // 依次填写Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径（例如D:\\localpath\\examplefile.txt）。Object完整路径中不能包含Bucket名称。
			        // 如果本地文件的完整路径中未指定本地路径（例如examplefile.txt），则默认从示例程序所属项目对应本地路径中上传文件。
			        await client.multipartUpload(fileName, file.file, {
			          progress: (p, cpt, res) => {
			            // 获取分片上传进度、断点和返回值。
			            this.percentage = (Math.floor(p * 100) / 100) * 100
			            if (p === 1) {
			              this.loading = false
			            }
			          },
			          parallel: 5, // 并发上传的分片数量
			          partSize: 1024 * 1024 * 20,
			          // headers,
			          // 指定meta参数，自定义Object的元信息。通过head接口可以获取到Object的meta数据。
			          meta: {
			            year: 2020,
			            people: 'test'
			          },
			          mime: file.type // 上传文件类型
			        })
			        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
			        const head = await client.head(fileName)
			        if (head.status === 200) {
			        	console.log(`${imgUrl}/${fileName}`)
			        	//赋值到相应的activity_video上
			        	for(let item of this.activity_video){
			        		if(item.uid==file.file.uid){
			        			item.url=`${imgUrl}/${fileName}`
			        		}
			        	}
			          // this.$set(this.courseForm, 'audition_link', `${imgUrl}/${fileName}`)
			          // this.$set(this.courseForm, 'audition_course_name', file.file.name)
			        }
			        else{
			        	console.log(`${imgUrl}/${fileName}`)
			        }
		        } catch (e) {
			        if (e.code === 'ConnectionTimeoutError') {
			          console.log('TimeoutError')
			        }
		       }
			},
		},
		mounted(){
			this.getList();
		}
	}
</script>
<style type="text/css">
	.pagination_box{
		    text-align: center;
		    display: flex;
		    justify-content: center;
		    width: 100%;
	}
	.query-item{
		margin-right:10px
	}
	.query-form{
		    padding:20px;
				    padding-bottom: 0px;
	}
	.add-box-css{
		width:100%;
		align-items: end;
    justify-content: end;
    padding: 0px 1rem 1rem 0px;
	}
</style>
